package com.ray.util.redis;

import java.util.Set;

import com.alibaba.fastjson.JSONObject;
import com.ray.bean.WorkOrderBean;
import com.ray.exception.ServiceException;
import com.ray.util.ConfigUtil;
import com.ray.util.SerializeUtil;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

/**
 * JedisPool
 * 
 * @author Shensg 2018年7月26日
 */
public class RedisCache {

	public static JedisPool jedisPool;

	public RedisCache() {
		throw new RuntimeException("此类不允许被new");
	}

	/**
	 * 构建redis连接池
	 * 
	 * @param ip
	 * @param port
	 * @return JedisPool
	 */
	public static JedisPool getPool() {
		if (jedisPool == null) {
			ConfigUtil.setPropertiesName("db.properties");
			ConfigUtil.init();
			JedisPoolConfig config = new JedisPoolConfig();
			// 控制一个pool可分配多少个jedis实例，通过pool.getResource()来获取；
			// 如果赋值为-1，则表示不限制；如果pool已经分配了maxActive个jedis实例，则此时pool的状态为exhausted(耗尽)。
			config.setMaxTotal(Integer.valueOf(ConfigUtil
					.getValue("redis.maxTotal")));
			// 控制一个pool最多有多少个状态为idle(空闲的)的jedis实例。
			config.setMaxIdle(Integer.valueOf(ConfigUtil
					.getValue("redis.maxIdle")));
			// 表示当borrow(引入)一个jedis实例时，最大的等待时间，如果超过等待时间，则直接抛出JedisConnectionException；
			config.setMaxWaitMillis(1000 * 30);
			// 在borrow一个jedis实例时，是否提前进行validate操作；如果为true，则得到的jedis实例均是可用的；
			config.setTestOnBorrow(true);
			String host = ConfigUtil.getValue("redis.url");
			String password = ConfigUtil.getValue("redis.password");
			int port = Integer.valueOf(ConfigUtil.getValue("redis.port"));
			jedisPool = new JedisPool(config, host, port, 3000, password);
		}
		return jedisPool;
	}

	/**
	 * 返还到连接池
	 * 
	 * @param pool
	 * @param redis
	 */
	public static void returnResource(JedisPool pool, Jedis redis) {
		if (redis != null) {
			redis.close();
		}
	}

	// 从redis缓存中查询，反序列化
	public static Object getDataFromRedis(String redisKey) {
		if(redisKey==null) {
			return null;
		}
		Jedis jedis = null;
		try {
			getPool();

			// 查询
			jedis = jedisPool.getResource();
			byte[] result = jedis.get(redisKey.getBytes("UTF-8"));

			// 如果查询没有为空
			if (null == result) {
				return null;
			}
			// 查询到了，反序列化
			return SerializeUtil.unSerialize(result);
		} catch (Exception e) {
			throw new ServiceException("redis:" + e.getMessage());
		} finally {
			returnResource(jedisPool, jedis);
		}
	}

	// 将数据库中查询到的数据放入redis
	public static void setDataToRedis(String redisKey, Object obj,
			String expiretime) {
		Jedis jedis = null;
		try {
			getPool();
			// 序列化
			byte[] bytes = SerializeUtil.serialize(obj);

			// 存入redis
			jedis = jedisPool.getResource();
			String success = jedis.set(redisKey.getBytes("UTF-8"), bytes);
			if (expiretime != null && !"".equals(expiretime)) {
				jedis.expire(redisKey.getBytes("UTF-8"),
						Integer.valueOf(expiretime));
			}
			if ("OK".equals(success)) {
				System.out.println("数据成功保存到redis...");
			}
		} catch (Exception e) {
			throw new ServiceException("redis:" + e.getMessage());
		} finally {
			returnResource(jedisPool, jedis);
		}
	}
	/**
	 * 删除key
	 * @param keys
	 * @return
	 */
	public static long delKey(String... keys) {
		Jedis jedis = null;
		try {
			getPool();
			jedis = jedisPool.getResource();
			long count = jedis.del(keys);
			return count;
		} catch (Exception e) {
			// TODO: handle exception
		} finally {
				returnResource(jedisPool, jedis);
		}
		return 0;
	}
	/**
	 * 更新key过期时间
	 * @param keys
	 * @param seconds
	 * @return
	 */
	public static long updateKeyExpire(String key,int seconds) {
		Jedis jedis = null;
		try {
			getPool();
			jedis = jedisPool.getResource();
			long count = jedis.expire(key, seconds);
			return count;
		} catch (Exception e) {
			// TODO: handle exception
		} finally {
				returnResource(jedisPool, jedis);
		}
		return 0;
	}

	public static void main(String[] args) {
		getPool();
		/*
		 * RedisCache.setDataToRedis("ssg", "123", "10");
		 * System.out.println(RedisCache.getDataFromRedis("ssg"));
		 */
		/*
		 * List<String> list = new ArrayList<String>(); list.add("1");
		 * RedisCache.setDataToRedis("ssg", list, null);
		 */
		/* System.out.println(RedisCache.getDataFromRedis("ssg")); */
		WorkOrderBean bean = new WorkOrderBean();
		bean.setCreateTime("2018");
		bean.setCustAddress("zhejiang");
		bean.setCustEvaluation("ok");
		RedisCache.setDataToRedis("铂亮光学/workOrder/addApplyWorkOrder",
				JSONObject.toJSON(bean), "10");
		Set<String> keys = jedisPool.getResource().keys(
				"*workOrder/addApplyWorkOrder*");

		System.out.println(keys);
		// jedisPool.getResource().flushAll();
		/*
		 * for (String key : keys) {
		 * System.out.println(jedisPool.getResource().del(key)); }
		 */
		System.out.println(updateKeyExpire("铂亮光学/workOrder/addApplyWorkOrder", 3));
	}
}